package com.example.wechathook.util;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage;

public class WechatUtil {

	public static String getTime() {
		Date date = new Date();
		return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(date);
	}

	public static String getType(Object obj) {
		if (obj == null) {
			return "null";
		}
		return obj.getClass().getName();
	}

	public static String getStr(Object obj) {
		if (obj == null) {
			return "null";
		}
		if (obj.getClass() == new byte[] {}.getClass()) {
			return encodeHexStr((byte[]) obj);
		}

		return obj.toString();
	}

	public static String encodeHexStr(byte[] data) {
		char[] toDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		int l = data.length;
		char[] out = new char[l << 1];
		for (int i = 0, j = 0; i < l; i++) {
			out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
			out[j++] = toDigits[0x0F & data[i]];
		}
		return new String(out);
	}

	/**
	 * 获得当前acitivity; 此方法只能够获当前线程中的activity，所以也就是只能够获得微信的界面；
	 * 
	 * @return
	 * @throws Exception
	 */
	private static Activity getGlobleActivity() throws Exception {
		Class activityThreadClass = Class.forName("android.app.ActivityThread");
		Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null);
		Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
		activitiesField.setAccessible(true);
		Map activities = (Map) activitiesField.get(activityThread);
		for (Object activityRecord : activities.values()) {
			Class activityRecordClass = activityRecord.getClass();
			Field pausedField = activityRecordClass.getDeclaredField("paused");
			pausedField.setAccessible(true);
			if (!pausedField.getBoolean(activityRecord)) {
				Field activityField = activityRecordClass.getDeclaredField("activity");
				activityField.setAccessible(true);
				return (Activity) activityField.get(activityRecord);
			}
		}
		return null;
	}

	/**
	 * 获取微信版本
	 * 
	 * @param packageName
	 * @param loadPackageParam
	 * @return
	 */
	public static String getWechatVersion(String packageName, XC_LoadPackage.LoadPackageParam lpp) {
		Object currentActivityThread = XposedHelpers.callStaticMethod(
				XposedHelpers.findClass("android.app.ActivityThread", null), "currentActivityThread");
		Context context = (Context) XposedHelpers.callMethod(currentActivityThread, "getSystemContext");
		try {
			String versionName = context.getPackageManager().getPackageInfo(packageName, 0).versionName;
			int uin = lpp.appInfo.uid;
			return versionName;
		} catch (Exception e) {
			e.printStackTrace();
			return "6.3.18";
		}
	}
}
